package com.fancy.learncenter.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.AudioBean;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonMediaBean;
import com.fancy.learncenter.bean.CartoonOptionsBean;
import com.fancy.learncenter.bean.CartoonStudentSubjectiveDataBean;
import com.fancy.learncenter.bean.ListenSpeakDetailDataBean;
import com.fancy.learncenter.bean.QuestionVOsBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.JumpIntentKey;
import com.fancy.learncenter.common.LoginUserSharePrefernce;
import com.fancy.learncenter.common.MAudioPlayer;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.ui.activity.CartoonFinishedActivity;
import com.fancy.learncenter.ui.activity.CartoonStaticsActivity;
import com.fancy.learncenter.ui.adapter.PreviewHomeworkAdapter;
import com.fancy.learncenter.ui.fragment.GrammarChooseFillBlankFragment;
import com.fancy.learncenter.ui.fragment.GrammarChooseFillBlankNewFragment;
import com.fancy.learncenter.ui.fragment.GrammarChooseFillBlankNewPreFragment;
import com.fancy.learncenter.ui.fragment.GrammarListenAndImageChooseTextFragment;
import com.fancy.learncenter.ui.fragment.GrammarListenAndImageChooseTextNewFragment;
import com.fancy.learncenter.ui.fragment.GrammarListenChooseImageFragment;
import com.fancy.learncenter.ui.fragment.GrammarListenChooseImageNewFragment;
import com.fancy.learncenter.ui.fragment.GrammarSeeImageChooseFragment;
import com.fancy.learncenter.ui.fragment.GrammarSeeImageChooseNewFragment;
import com.fancy.learncenter.ui.fragment.MyBaseFragment;
import com.fancy.learncenter.ui.fragment.SeeWordPuzzleFragment;
import com.fancy.learncenter.ui.fragment.SeeWordPuzzleNewFragment;
import com.fancy.learncenter.ui.fragment.WordFillBlankFragment;
import com.fancy.learncenter.ui.fragment.WordFillBlankNewFragment;
import com.fancy.learncenter.ui.fragment.WordListenChooseImageFragment;
import com.fancy.learncenter.ui.fragment.WordListenChooseImageNewFragment;
import com.fancy.learncenter.ui.fragment.WordSeeImageChooseWordFragment;
import com.fancy.learncenter.ui.fragment.WordSeeImageChooseWordNewFragment;
import com.fancy.learncenter.ui.fragment.WordSeeImageListenSpellFragment;
import com.fancy.learncenter.ui.fragment.WordSeeImageListenSpellNewFragment;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Hyy on 2016/12/21.
 */

public class Utils {
    private static float mDensity = DisplayMetrics.DENSITY_DEFAULT;

    public static int getStatusBarHeight() {
        int result = 0;
        int resourceId = MyApplication.context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = MyApplication.context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public static int dip2pix(Context context, int dip) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return (int) (dm.density * (float) dip);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    //  jason串转带泛型的bean类 。
    public static <T> BaseBean<T> fromJsonObject(String reader, Class<T> clazz) {
        Type type = new ParameterizedTypeImpl(BaseBean.class, new Class[]{clazz});
        return new Gson().fromJson(reader, type);
    }


    public static class ParameterizedTypeImpl implements ParameterizedType {
        private final Class raw;
        private final Type[] args;

        public ParameterizedTypeImpl(Class raw, Type[] args) {
            this.raw = raw;
            this.args = args != null ? args : new Type[0];
        }

        @Override
        public Type[] getActualTypeArguments() {
            return args;
        }

        @Override
        public Type getRawType() {
            return raw;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    }

    //获取本地文件夹中的音频
    public static ArrayList<AudioBean> getLoctionAudio() {
        //selection: 指定查询条件
        String selection = MediaStore.Audio.Media.DATA + " like ?";
        //设定查询目录
        //定义selectionArgs：参数selection里有？这个符号是，这里可以以实际值代替这个问号。如果//selection这个没有？的话，那么这个String数组可以为null。
        String[] selectionArgs = {FileUtils.getRecorderAudioPath().substring(0, FileUtils.getRecorderAudioPath().length() - 1) + "%"};
        Cursor cursor = MyApplication.context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Audio.Media.TITLE,
                        MediaStore.Audio.Media.DURATION,
                        MediaStore.Audio.Media.ARTIST,
                        MediaStore.Audio.Media.DISPLAY_NAME,
                        MediaStore.Audio.Media.DATA,
                        MediaStore.Audio.Media.ALBUM_ID},
                selection, selectionArgs, null);

        ArrayList<AudioBean> audioBeens = new ArrayList<AudioBean>();
        for (int i = 0; i < cursor.getCount(); i++) {
//            AudioBean mp3Info = new AudioBean();
            //新建一个歌曲对象,将从cursor里读出的信息存放进去,直到取完cursor里面的内容为止.
            cursor.moveToNext();
//            long id = cursor.getLong(cursor
//                    .getColumnIndex(MediaStore.Audio.Media._ID));    //音乐id
            AudioBean audioBean = new AudioBean();

            String title = cursor.getString((cursor
                    .getColumnIndex(MediaStore.Audio.Media.TITLE)));//音乐标题

            long duration = cursor.getLong(cursor
                    .getColumnIndex(MediaStore.Audio.Media.DURATION));//时长
            audioBean.setResourceDuration((int) (duration / 1000));

            String url = cursor.getString(cursor
                    .getColumnIndex(MediaStore.Audio.Media.DATA));    //文件路径
            audioBean.setPlayLink(url);

//            String artist = cursor.getString(cursor
//                    .getColumnIndex(MediaStore.Audio.Media.ARTIST));//艺术家
//
//            long size = cursor.getLong(cursor
//                    .getColumnIndex(MediaStore.Audio.Media.SIZE));    //文件大小
//
//            String album = cursor.getString(cursor
//                    .getColumnIndex(MediaStore.Audio.Media.ALBUM)); //唱片图片
//
//            long album_id = cursor.getLong(cursor
//                    .getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)); //唱片图片ID
//
//            int isMusic = cursor.getInt(cursor
//                    .getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));//是否为音乐

            audioBeens.add(audioBean);
        }

        cursor.close();

        return audioBeens;
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][34578]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) {
            return false;
        } else return mobiles.matches(telRegex);
    }


    public static int getScreeWidth() {
        WindowManager wm = (WindowManager) MyApplication.context
                .getSystemService(Context.WINDOW_SERVICE);

        return wm.getDefaultDisplay().getWidth();
    }

    public static int getScreeHeight() {
        WindowManager wm = (WindowManager) MyApplication.context
                .getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getHeight();
    }

    /**
     * 获取版本名称
     *
     * @return 当前应用的版本名称
     */
    public static String getVersionName() {
        try {
            PackageManager manager = MyApplication.context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(MyApplication.context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "0.00";
        }
    }


    /**
     * 获取版本号
     *
     * @return 当前应用的更新次数
     */
    public static int getVersionCode() {
        try {
            PackageManager manager = MyApplication.context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(MyApplication.context.getPackageName(), 0);
            int version = info.versionCode;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static long getCurrentTime() {
        return System.currentTimeMillis() / 1000;
    }


    /**
     * 获取和服务端相同时间
     *
     * @return
     */
    public static long getCurrentTimeMillis() {
        return (System.currentTimeMillis() / 1000 + LoginUserSharePrefernce.getTime());
    }

    public static Uri getImgUri(String imgUrl) {
        if (imgUrl == null)
            return Uri.parse("");
        else if (imgUrl.contains("http"))
            return Uri.parse(imgUrl);
        else
            return Uri.parse("http://image.fancyedu.com/" + imgUrl);
    }

    public static String getImgUrlUtil(String imgUrl) {
        if (imgUrl == null)
            return "";
        else if (imgUrl.contains("http"))
            return imgUrl;
        else
            return "http://image.fancyedu.com/" + imgUrl;
    }


    /**
     * 非凡学习
     *
     * @param urlId
     * @return
     */
    public static String getUrlIndex(String urlId) {
        String url = "";
        try {
            JSONObject jsonObject = new JSONObject(LoginUserSharePrefernce.getUrlConfig());
            JSONArray jsonArray = jsonObject.optJSONArray("UrlConfig");
            int length = jsonArray.length();
            for (int i = 0; i < length; i++) {
                JSONObject urlJson = jsonArray.optJSONObject(i);
                if (urlId.equals(urlJson.optString("OperationId"))) {
                    url = urlJson.optString("OperationTip");
                    return url;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return url;
    }


    public static String getPicPath(String picPath, int width, int hight) {
        return picPath + "?x-oss-process=image/resize,m_fill,w_" + width + ",h_" + hight + ",limit_0/auto-orient,0/format,png";
    }


    /**
     * 题型跳转
     *
     * @param transaction
     * @param questionBankList
     * @param index
     * @param resId
     * @param context
     * @param homePackageId    作业包ID
     */
    @SuppressLint("ResourceType")
    public static void switchFragment(Activity context, FragmentTransaction transaction, ArrayList<QuestionVOsBean> questionBankList, int index, int resId, JumpIntentKey.QUESTION_ENTER_TYPE type, String homePackageId, String studentHomeworkId, String lessonNameStr, String unitNameStr) {

        Fragment fragment = null;
        int totalNum = questionBankList.size();
        switch (type) {
            case DO_WORK:
            case CONTINUE_WORK:
                if (index == totalNum) {
                    Intent intent = new Intent(context, CartoonStaticsActivity.class);
                    intent.putExtra(JumpIntentKey.QUESTION_ENTER, JumpIntentKey.QUESTION_ENTER_TYPE.FINISH_WORK);
                    intent.putExtra(JumpIntentKey.STUDENTHOMEWORKID, studentHomeworkId);
                    intent.putExtra(JumpIntentKey.HOMEWORK_PACKAGE_ID, homePackageId);
                    intent.putExtra(JumpIntentKey.QUESTION_NUM, String.valueOf(totalNum));
                    intent.putExtra(JumpIntentKey.LESSON_NAME, lessonNameStr);
                    intent.putExtra(JumpIntentKey.UNIT_NAME, unitNameStr);
                    context.startActivity(intent);
                    context.finish();
                    return;
                }

                break;
            case DO_IT_AGAIN:
                if (index == totalNum) {
                    Bundle bundle2 = new Bundle();
                    bundle2.putString(JumpIntentKey.HOMEWORK_PACKAGE_ID, homePackageId);
                    bundle2.putSerializable(JumpIntentKey.QUESTION_ENTER, type);
                    bundle2.putString(JumpIntentKey.QUESTION_NUM, String.valueOf(totalNum));
                    Intent intentFinish = new Intent(context, CartoonFinishedActivity.class);
                    intentFinish.putExtras(bundle2);
                    context.startActivity(intentFinish);
                    context.finish();
                    return;
                }
                break;
            case ERROR_KINDS:
            case HAS_CORRECTED:
            case NOT_CORRECTED:
                if (index == totalNum) {
                    return;
                }
                break;
        }

        QuestionVOsBean bean = questionBankList.get(index);

        switch (bean.getAppPageKey()) {
            case Constant.LCTP: //听音选图 选项是图片 题目 ：文本和音频
                CartoonOptionsBean optionsBeanListen = bean.getOptions();
                if (optionsBeanListen != null) {
                    List<CartoonMediaBean> imageList = optionsBeanListen.getImages();
                    if (imageList != null && imageList.size() == 2) {
                        fragment = GrammarListenChooseImageFragment.newInstance(questionBankList, index, totalNum, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                    } else {
                        fragment = WordListenChooseImageFragment.newInstance(questionBankList, index, totalNum, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                    }
                }


                break;
            case Constant.LPTPT://"看词拼图":
                fragment = SeeWordPuzzleFragment.newInstance(questionBankList, index, totalNum, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
            case Constant.LCTW:// "看图选词":
                fragment = WordSeeImageChooseWordFragment.newInstance(questionBankList, index, totalNum, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
            case Constant.LLAS:// "听音拼写":
                fragment = WordSeeImageListenSpellFragment.newInstance(questionBankList, index, totalNum, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
            case Constant.USFB:// "选词填空":
                fragment = GrammarChooseFillBlankFragment.newInstance(questionBankList, index, totalNum, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
            case Constant.LAC:// "听音选择":  ／／选项 是文本
//                if (optionsBean != null) {
//                    List<CartoonMediaBean> imageList = optionsBean.getImages();
//                    if (imageList != null && imageList.size() > 0) {
//                        fragment = GrammarListenChooseImageFragment.newInstance(questionBankList, index, totalNum, type, homePackageId, studentHomeworkId);
//                    } else if (stemsBean != null) {
//                        List<CartoonMediaBean> imageStemsList = stemsBean.getImages();
//                        if (imageStemsList != null && imageStemsList.size() > 0) {
                fragment = GrammarListenAndImageChooseTextFragment.newInstance(questionBankList, index, totalNum, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
//                        } else {
//                            fragment = GrammarListenChooseTextFragment.newInstance(questionBankList, index, totalNum, type, homePackageId, studentHomeworkId);
//                        }
//                    }
//                }
                break;
            case Constant.LPC: //看图选择
                fragment = GrammarSeeImageChooseFragment.newInstance(questionBankList, index, totalNum, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
            case Constant.FTB://填空
                fragment = WordFillBlankFragment.newInstance(questionBankList, index, totalNum, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
        }
        transaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
        transaction.replace(resId, fragment);
        transaction.show(fragment).commit();
    }

    /**
     * 题型跳转
     *
     * @param transaction
     * @param questionBankList
     * @param index
     * @param resId
     * @param context
     * @param homePackageId    作业包ID
     */
    @SuppressLint("ResourceType")
    public static void switchNewFragment(Activity context, FragmentTransaction transaction, ArrayList<QuestionVOsBean> questionBankList, int index, int resId, JumpIntentKey.QUESTION_ENTER_TYPE type, String homePackageId, String studentHomeworkId, String lessonNameStr, String unitNameStr) {

        Fragment fragment = null;
        int totalNum = questionBankList.size();
        switch (type) {
            case DO_WORK:
            case CONTINUE_WORK:
                if (index == totalNum) {
                    Intent intent = new Intent(context, CartoonStaticsActivity.class);
                    intent.putExtra(JumpIntentKey.QUESTION_ENTER, JumpIntentKey.QUESTION_ENTER_TYPE.FINISH_WORK);
                    intent.putExtra(JumpIntentKey.STUDENTHOMEWORKID, studentHomeworkId);
                    intent.putExtra(JumpIntentKey.HOMEWORK_PACKAGE_ID, homePackageId);
                    intent.putExtra(JumpIntentKey.QUESTION_NUM, String.valueOf(totalNum));
                    intent.putExtra(JumpIntentKey.LESSON_NAME, lessonNameStr);
                    intent.putExtra(JumpIntentKey.UNIT_NAME, unitNameStr);
                    context.startActivity(intent);
                    context.finish();
                    return;
                }

                break;
            case DO_IT_AGAIN:
                if (index == totalNum) {
                    Bundle bundle2 = new Bundle();
                    bundle2.putString(JumpIntentKey.HOMEWORK_PACKAGE_ID, homePackageId);
                    bundle2.putSerializable(JumpIntentKey.QUESTION_ENTER, type);
                    bundle2.putString(JumpIntentKey.QUESTION_NUM, String.valueOf(totalNum));
                    Intent intentFinish = new Intent(context, CartoonFinishedActivity.class);
                    intentFinish.putExtras(bundle2);
                    context.startActivity(intentFinish);
                    context.finish();
                    return;
                }
                break;
            case ERROR_KINDS:
            case HAS_CORRECTED:
            case NOT_CORRECTED:
                if (index == totalNum) {
                    return;
                }
                break;
        }

        QuestionVOsBean bean = questionBankList.get(index);

        switch (bean.getAppPageKey()) {
            case Constant.LCTP: //听音选图 选项是图片 题目 ：文本和音频
                CartoonOptionsBean optionsBeanListen = bean.getOptions();
                if (optionsBeanListen != null) {
                    List<CartoonMediaBean> imageList = optionsBeanListen.getImages();
                    if (imageList != null && imageList.size() == 2) {
                        fragment = GrammarListenChooseImageNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                    } else {
                        fragment = WordListenChooseImageNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                    }
                }

                break;
            case Constant.LPTPT://"看词拼图":
                fragment = SeeWordPuzzleNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
            case Constant.LCTW:// "看图选词":
                fragment = WordSeeImageChooseWordNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
            case Constant.LLAS:// "听音拼写":
                fragment = WordSeeImageListenSpellNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
            case Constant.USFB:// "选词填空":

                fragment = GrammarChooseFillBlankNewPreFragment.newInstance(questionBankList, index, totalNum, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
//                fragment = GrammarChooseFillBlankNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
            case Constant.LAC:// "听音选择":  ／／选项 是文本
                fragment = GrammarListenAndImageChooseTextNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
            case Constant.LPC: //看图选择
                fragment = GrammarSeeImageChooseNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
            case Constant.FTB://填空
                fragment = WordFillBlankNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
        }
        transaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
        transaction.replace(resId, fragment);
        transaction.show(fragment).commit();
    }

    /**
     * 题型跳转
     *
     * @param questionBankList
     * @param index
     * @param context
     * @param homePackageId    作业包ID
     */
    public static List<MyBaseFragment> getFragment(Activity context, ArrayList<QuestionVOsBean> questionBankList, int index, JumpIntentKey.QUESTION_ENTER_TYPE type, String homePackageId, String studentHomeworkId, String lessonNameStr, String unitNameStr) {
        List<MyBaseFragment> fragmentDatas = new ArrayList<>();


        for (int i = 0; i < questionBankList.size(); i++) {
            MyBaseFragment fragment = null;
            QuestionVOsBean bean = questionBankList.get(i);

            switch (bean.getAppPageKey()) {
                case Constant.LCTP: //听音选图 选项是图片 题目 ：文本和音频
                    CartoonOptionsBean optionsBeanListen = bean.getOptions();
                    if (optionsBeanListen != null) {
                        List<CartoonMediaBean> imageList = optionsBeanListen.getImages();
                        if (imageList != null && imageList.size() == 2) {
                            fragment = GrammarListenChooseImageNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                        } else {
                            fragment = WordListenChooseImageNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                        }
                    }

                    break;
                case Constant.LPTPT://"看词拼图":
                    fragment = SeeWordPuzzleNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                    break;
                case Constant.LCTW:// "看图选词":
                    fragment = WordSeeImageChooseWordNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                    break;
                case Constant.LLAS:// "听音拼写":
                    fragment = WordSeeImageListenSpellNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                    break;
                case Constant.USFB:// "选词填空":
                    fragment = GrammarChooseFillBlankNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                    break;
                case Constant.LAC:// "听音选择":  ／／选项 是文本
                    fragment = GrammarListenAndImageChooseTextNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                    break;
                case Constant.LPC: //看图选择
                    fragment = GrammarSeeImageChooseNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                    break;
                case Constant.FTB://填空
                    fragment = WordFillBlankNewFragment.newInstance(bean, index, 0, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                    break;
            }

            if (fragment != null) {
                fragmentDatas.add(fragment);
            }

        }
        return fragmentDatas;

    }


    public static String getCartoonFrgName(MyBaseFragment myBaseFragment) {

        if (myBaseFragment instanceof GrammarListenChooseImageNewFragment || myBaseFragment instanceof WordListenChooseImageNewFragment) {
            return "听音选图";
        } else if (myBaseFragment instanceof SeeWordPuzzleNewFragment) {
            return "看词拼图";
        } else if (myBaseFragment instanceof WordSeeImageChooseWordNewFragment) {
            return "看图选词";
        } else if (myBaseFragment instanceof WordSeeImageListenSpellNewFragment) {
            return "听音拼写";
        } else if (myBaseFragment instanceof GrammarChooseFillBlankNewFragment) {
            return "选词填空";
        } else if (myBaseFragment instanceof GrammarSeeImageChooseNewFragment) {
            return "听音选择";
        } else if (myBaseFragment instanceof GrammarSeeImageChooseNewFragment) {
            return "看图选择";
        } else if (myBaseFragment instanceof WordFillBlankNewFragment) {
            return "填空";
        }


        return "其他";
    }

    public static boolean isNumeric(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }


    /**
     * 提交按钮状态变化
     */
    public static void notifyButtonBg(JumpIntentKey.CARTOON_BUTTON_STATUS buttonStatus, ImageView commitImage) {

        switch (buttonStatus) {
            case STATUS_GRAY:
                commitImage.setImageResource(R.mipmap.commit_gray);
                commitImage.setEnabled(false);
                commitImage.setVisibility(View.VISIBLE);
                break;
            case STATUS_LIGHT:
                commitImage.setImageResource(R.mipmap.commit_light);
                commitImage.setEnabled(true);
                commitImage.setVisibility(View.VISIBLE);
                break;
            case STATUS_SEE_ANSWER:
                commitImage.setVisibility(View.VISIBLE);

                commitImage.setImageResource(R.mipmap.cartoon_see_answer);

                commitImage.setEnabled(true);
                break;
            case STATUS_ANALYSIS:
                commitImage.setImageResource(R.mipmap.cartoon_analysis);
                commitImage.setEnabled(true);
                commitImage.setVisibility(View.VISIBLE);
                break;
            case STATUS_HIDE:
                commitImage.setImageResource(R.mipmap.commit_gray);
                commitImage.setEnabled(true);
                commitImage.setVisibility(View.GONE);
                break;

        }

    }


    /**
     * 比较两个list是否相等
     *
     * @param a
     * @param b
     * @return
     */
    public static boolean compare(List<String> a, List<String> b) {

        if (a == null || b == null) {
            return false;
        }
        if (a.size() != b.size())
            return false;
        for (int i = 0; i < a.size(); i++) {
            if (!a.get(i).equals(b.get(i)))
                return false;
        }
        return true;
    }


    /**
     * 题型里播放音频
     *
     * @param audioPlayer
     * @param audioUrl
     * @param imageVoice
     */
    public static void playOrPauseAudio(MAudioPlayer audioPlayer, String audioUrl, final ImageView imageVoice) {


        if (audioPlayer != null && audioPlayer.isPlaying()) {
            audioPlayer.stop();
            return;
        }
        if (audioPlayer == null) {
            audioPlayer = new MAudioPlayer();
        }
        imageVoice.setImageResource(R.drawable.cartoon_play_sound_animation);
        final AnimationDrawable animationDrawable = (AnimationDrawable) imageVoice.getDrawable();
        final MAudioPlayer finalAudioPlayer = audioPlayer;

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                imageVoice.setEnabled(false);
                animationDrawable.start();
                Log.i("imageVoice------+++", "start" + imageVoice.getDrawable().toString());
            }
        }, 0);


        audioPlayer.setAudioPlayerStatus(new MAudioPlayer.AudioPlayerStatus() {
            @Override
            public void playerPause() {
                Log.i("imageVoice------+++", "pause--" + imageVoice.getDrawable().toString());
                animationDrawable.stop();
                imageVoice.setEnabled(true);
                imageVoice.setImageResource(R.mipmap.cartoon_sound_animation_3);
                Log.i("imageVoice------+++", "pause--" + imageVoice.getDrawable().toString());
            }

            @Override
            public void playerCompletion(MediaPlayer mp) {
                animationDrawable.stop();
                imageVoice.setEnabled(true);
                imageVoice.setImageResource(R.mipmap.cartoon_sound_animation_3);
            }

            @Override
            public void playerPrepared(MediaPlayer mp) {

                finalAudioPlayer.play();
            }

            @Override
            public void playerStart() {
                Log.i("imageVoice------+++", "start--" + imageVoice.getDrawable().toString());
            }

            @Override
            public void playerError(MediaPlayer mp, int what, int extra) {
                Log.i("imageVoice------+++", "stop--" + imageVoice.getDrawable().toString());
            }
        });
        audioPlayer.playUrl(audioUrl);
    }


    /**
     * 题型里播放音频
     *
     * @param audioUrl
     * @param imageVoice
     */
    public static void playOrPauseAudio(PreviewHomeworkAdapter adapter, String audioUrl, final ImageView imageVoice) {


        if (adapter.getAudioPlayer() != null && adapter.getAudioPlayer().isPlaying()) {
            adapter.getAudioPlayer().stop();
            return;
        }
        if (adapter.getAudioPlayer() == null) {
            adapter.setAudioPlayer(new MAudioPlayer());
        }
        imageVoice.setImageResource(R.drawable.cartoon_play_sound_animation);
        final AnimationDrawable animationDrawable = (AnimationDrawable) imageVoice.getDrawable();
        final MAudioPlayer finalAudioPlayer = adapter.getAudioPlayer();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                imageVoice.setEnabled(false);
                animationDrawable.start();
                Log.i("imageVoice------+++", "start" + imageVoice.getDrawable().toString());
            }
        }, 0);


        adapter.getAudioPlayer().setAudioPlayerStatus(new MAudioPlayer.AudioPlayerStatus() {
            @Override
            public void playerPause() {
                Log.i("imageVoice------+++", "pause--" + imageVoice.getDrawable().toString());
                animationDrawable.stop();
                imageVoice.setEnabled(true);
                imageVoice.setImageResource(R.mipmap.cartoon_sound_animation_3);
                Log.i("imageVoice------+++", "pause--" + imageVoice.getDrawable().toString());
            }

            @Override
            public void playerCompletion(MediaPlayer mp) {
                animationDrawable.stop();
                imageVoice.setEnabled(true);
                imageVoice.setImageResource(R.mipmap.cartoon_sound_animation_3);
            }

            @Override
            public void playerPrepared(MediaPlayer mp) {

                finalAudioPlayer.play();
            }

            @Override
            public void playerStart() {
                Log.i("imageVoice------+++", "start--" + imageVoice.getDrawable().toString());
            }

            @Override
            public void playerError(MediaPlayer mp, int what, int extra) {
                Log.i("imageVoice------+++", "stop--" + imageVoice.getDrawable().toString());
            }
        });
        adapter.getAudioPlayer().playUrl(audioUrl);
    }

    /**
     * 停止音频播放
     *
     * @param imageVoice
     */
    public static void stopVoiceImage(ImageView imageVoice) {


        if (imageVoice != null) {
            Log.i("imageVoice----", "imageVoice+++");
            Log.i("imageVoice----", imageVoice.getDrawable().toString());
            if (imageVoice.getDrawable() instanceof AnimationDrawable) {
                Log.i("imageVoice----", "imageVoice");
                AnimationDrawable animationDrawable = (AnimationDrawable) imageVoice.getDrawable();
                if (animationDrawable != null) {
                    animationDrawable.stop();
                    imageVoice.setEnabled(true);
                    imageVoice.setImageResource(R.mipmap.cartoon_sound_animation_3);
                }
            }
        }
    }


    /**
     * 方法名称:transMapToString
     * 传入参数:map
     * 返回值:String 形如 username'chenziwen^password'1234
     */
    public static String transMapToString(Map map) {
        java.util.Map.Entry entry;
        StringBuffer sb = new StringBuffer();
        for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext(); ) {
            entry = (java.util.Map.Entry) iterator.next();
            sb.append(entry.getKey().toString()).append("'").append(null == entry.getValue() ? "" :
                    entry.getValue().toString()).append(iterator.hasNext() ? "^" : "");
        }
        return sb.toString();
    }

    /**
     * 方法名称:transStringToMap
     * 传入参数:mapString 形如 username'chenziwen^password'1234
     * 返回值:Map
     */
    public static Map transStringToMap(String mapString) {
        Map map = new HashMap();
        java.util.StringTokenizer items;
        for (StringTokenizer entrys = new StringTokenizer(mapString, "^"); entrys.hasMoreTokens();
             map.put(items.nextToken(), items.hasMoreTokens() ? ((Object) (items.nextToken())) : null))
            items = new StringTokenizer(entrys.nextToken(), "'");
        return map;
    }


    public static String LOCALRE_CORDER_DIVIDE = "&&";


    /**
     * 以类目纬度，数据保存到本地
     */
    public static void saveSudentFile(String fileName, ListenSpeakDetailDataBean dataBean) {
        Gson gson = new Gson();
        String str = gson.toJson(dataBean);
        FileUtils.creatFile(fileName);
        FileUtils.saveStringToFile(fileName, str);
    }

    /**
     * 以题目纬度，存取数据到本地
     * <p>
     * * @param itemData
     */
    public static void saveSudentKeyValueRes(List<CartoonStudentSubjectiveDataBean> itemData) {
        Gson gson = new Gson();
        Map resDatas;
        String readResultStr = FileUtils.readFromSD(FileUtils.getSutendRes());
        if (!TextUtils.isEmpty(readResultStr)) {
            resDatas = Utils.transStringToMap(readResultStr);
        } else {
            resDatas = new HashMap();
        }
        for (int i = 0; i < itemData.size(); i++) {

            String resourceStr = gson.toJson(itemData.get(i));

            resDatas.put(itemData.get(i).getSubjectQuestionId() + "", resourceStr);
        }

        String resource = Utils.transMapToString(resDatas);

        FileUtils.saveStringToFile(FileUtils.getSutendRes(), resource);
    }


    /**
     * 以题目纬度，存取客观题数据到本地
     * <p>
     * * @param itemData
     */
    public static void saveQuestionKeyValueRes(String fileName, List<QuestionVOsBean> itemData) {
        Gson gson = new Gson();
        Map resDatas;
        String readResultStr = FileUtils.readFromSD(fileName);
        if (!TextUtils.isEmpty(readResultStr)) {
            resDatas = Utils.transStringToMap(readResultStr);
        } else {
            resDatas = new HashMap();
        }
        for (int i = 0; i < itemData.size(); i++) {

            String resourceStr = gson.toJson(itemData.get(i));

            resDatas.put(itemData.get(i).getQuestionId() + "", resourceStr);
        }

        String resource = Utils.transMapToString(resDatas);

        FileUtils.saveStringToFile(fileName, resource);
    }

    /**
     * 获取客观题所有题的资源
     *
     * @return
     */
    public static Map<String, String> getQuestionKeyValue(String fileName) {
        Map<String, String> resDatas = new HashMap();

        String readResultStr = FileUtils.readFromSD(fileName);

        if (!TextUtils.isEmpty(readResultStr)) {
            resDatas = Utils.transStringToMap(readResultStr);
        }

        return resDatas;
    }


    /**
     * 获取学生端，题目所有资源
     *
     * @return <String,CartoonStudentSubjectiveDataBean (json) ></>
     */
    public static Map<String, String> getSudentKeyValueRes() {
        Map<String, String> resDatas = new HashMap();

        String readResultStr = FileUtils.readFromSD(FileUtils.getSutendRes());

        if (!TextUtils.isEmpty(readResultStr)) {
            resDatas = Utils.transStringToMap(readResultStr);
        }

        LogUtil.MyLog("getSudentKeyValueRes", "=====getSudentKeyValueRes====" + resDatas.size());
        return resDatas;
    }

    /**
     * 保存录音资源到本地
     *
     * @param fileName      文件地址
     * @param resId
     * @param coverImg
     * @param questionsName
     * @param duration
     * @param endTime
     */
    public static void saveLocalRecorder(String fileName, String resId, String coverImg, String questionsName, long duration, long endTime) {
        Map resDatas;
        String readResultStr = FileUtils.readFromSD(FileUtils.getSutendLocalRes());
        if (!TextUtils.isEmpty(readResultStr)) {
            resDatas = Utils.transStringToMap(readResultStr);
        } else {
            resDatas = new HashMap();
        }

        if (TextUtils.isEmpty(coverImg)) {
            coverImg = " ";
        }
        if (TextUtils.isEmpty(questionsName)) {
            questionsName = " ";
        }
        String res = coverImg + LOCALRE_CORDER_DIVIDE + questionsName + LOCALRE_CORDER_DIVIDE + duration + LOCALRE_CORDER_DIVIDE + DataUtil.getDateTime(endTime, "yyyy-MM-dd HH:mm:ss") + "&&" + resId;
        resDatas.put(fileName + "", res);

        String resource = Utils.transMapToString(resDatas);

        FileUtils.saveStringToFile(FileUtils.getSutendLocalRes(), resource);
    }


}
